/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-16 21:21:17
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-05-29 15:22:02
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useEffect, useRef, useState } from 'react'
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { Button, Popconfirm, Space } from 'antd';
import { SysJobLogDomain } from '@/type.d/monitor/jobLog';
import ResizeTable from '@/components/ResizeTable';
import { DictDataDomain } from '@/type.d/system';
import { pageInfo } from '@/type.d/ajaxResult';
import PageDiv from '@/components/PageDiv';
import { useStore } from '@/store';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    QueryFilter,
} from '@ant-design/pro-components';
import {
    listJobLog,
    delJobLog,
} from '@/api/monitor/jobLog';
import SysJobLogCard from './jobLogCard';

import './index.less';
import { useParams } from 'react-router-dom';

const JobLog: React.FC = () => {
    const { layoutStore } = useStore();
    let params = useParams();
    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysJobLogDomain>>();
    const [queryValue, setQueryValue] = useState<SysJobLogDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<SysJobLogDomain[]>([]);

    const [sysCommonStatusOptions, setSysCommonStatusOptions] = useState<any[]>([]);

    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const [cardData, setCardData] = useState<SysJobLogDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);


    const newdata = {}

    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysJobLogDomain>[] = [
        {
            title: '任务名称',
            dataIndex: 'jobName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '任务组名',
            dataIndex: 'jobGroup',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '调用目标字符串',
            dataIndex: 'invokeTarget',
        },
        {
            title: '日志信息',
            dataIndex: 'jobMessage',
        },
        {
            title: '执行状态',
            dataIndex: 'status',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysCommonStatusOptions
            },
        },
        {
            title: '异常信息',
            dataIndex: 'exceptionInfo',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: SysJobLogDomain) => [
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" onClick={() => {
                    toCard(entity, true);
                }}>修改</a>,
                <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                    onDelete(entity)
                }}>
                    <a key="delete">删除</a>
                </Popconfirm>

            ],
        },
    ];

    const toCard = (data: SysJobLogDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: SysJobLogDomain) => {
        toCard(data)
    }


    const onDelete = (dedata: SysJobLogDomain) => {
        if (dedata.jobLogId) {
            layoutStore.OpenSpanning()
            delJobLog(dedata.jobLogId).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.jobLogId !== dedata.jobLogId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }


    const headButton = () => {
        return <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard(newdata, true)}
            >
                新增
            </Button>
        </Space>
    }

    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_common_status').then((res) => {
            const data = res.data;
            if (data['sysCommonStatus']) {
                const d: [] = data['sysCommonStatus'];
                setSysCommonStatusOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))

            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])


    useEffect(() => {
        if (params && params.jobName) {
            queryformRef.current?.setFieldsValue({...queryValue,jobName: params.jobName})
            queryformRef.current?.submit()
        }
    }, [params,params.jobName])

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,, pageInfo.pageSize])


    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listJobLog(_data).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])


    return (
        <PageDiv>{
            pageStatus === 'List' ? <PageDiv>
                <QueryFilter<SysJobLogDomain>
                    defaultCollapsed
                    split
                    span={4}
                    onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                    formRef={queryformRef}>
                    <ProFormText key='jobName' name="jobName" label="任务名称" />

                    <ProFormText key='jobGroup' name="jobGroup" label="任务组名" />



                    <ProFormSelect key='status' name="status"
                        label="执行状态"
                        options={sysCommonStatusOptions}
                    />


                </QueryFilter>
                <ResizeTable<SysJobLogDomain>
                    onRow={record => {
                        return {
                            onDoubleClick: event => {
                                onView(record)
                            },
                        };
                    }}
                    dataSource={tableListDataSource}
                    actionRef={actionRef}
                    columns={columns}
                    cardBordered
                    revalidateOnFocus={false}
                    pagination={{
                        ...pageInfo,
                        showTitle: false,
                        onChange: onPageChange
                    }}
                    headerTitle={headButton()}
                >
                </ResizeTable>
            </PageDiv> :
                <SysJobLogCard
                    onBack={() => setPageStatus('List')}
                    isedit={isedit}
                    setIsedit={setIsedit}
                    sysCommonStatusOptions={sysCommonStatusOptions}
                    cardData={cardData}
                    newdata={newdata}
                    tableListDataSource={tableListDataSource}
                    setTableListDataSource={setTableListDataSource} />}
        </PageDiv>

    )
}
export default JobLog;